import { Options } from '../entity/Options';
import path, { resolve } from 'node:path';
import { getZipName } from './parameter';
import { log } from './log';
import * as child_process from 'node:child_process';

const EXE_NAME = {
  win: 'nw.exe',
  osx: 'nwjs.app/Contents/MacOS/nwjs',
  linux: 'nw',
};

export async function startRunner(options: Options) {
  log.info(`即将启动...`);
  return new Promise<void>((resolve1, reject) => {
    let nwDir = `${options.cacheDir}/${getZipName(options)}`;

    let command = path.resolve(nwDir, EXE_NAME[options.platform]);

    log.debug(`启动命令为: '${command}', 参数: '${resolve(options.srcDir)}'`);
    const nwProcess = child_process.spawn(
        command,
        [resolve(options.srcDir)],
        {
          stdio: 'inherit',
        },
    );
    nwProcess.on('data', args => {
      log.debug(`执行事件 data: ${args}`);
    });
    nwProcess.on('exit', (code, signal) => {
      log.debug(`执行事件 exit, code: ${code}, signal: ${signal}`);
    });
    nwProcess.on('spawn', () => {
      log.debug(`执行事件 spawn`);
    });
    nwProcess.on('disconnect', () => {
      log.debug(`执行事件 disconnect`);
    });
    nwProcess.on('message', message => {
      log.debug(`执行事件 message: ${message}`);
    });
    nwProcess.on('close', () => {
      log.debug(`执行事件 close`);
      process.nextTick(function () {
        process.exit(0);
      });
      resolve1();
    });
    nwProcess.on('error', (error) => {
      log.error(`执行事件 error: ${error}`);
      reject(error);
    });


  });
}
